package com.app.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.app.mapper.FwMapper;
import com.app.mapper.TenantRelationshipMapper;
import com.app.mapper.UserMapper;
import com.app.mapper.YonghuMapper;
import com.app.model.Fw;
import com.app.model.TenantRelationship;
import com.app.model.User;
import com.app.model.Yonghu;
import com.app.util.IDCardValidator;
import com.app.util.PhoneValidator;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import static com.app.controller.FwController.generateStringFromTimestamp;

/**
 * <p>
 * 承租人关系记录表 前端控制器
 * </p>
 *
 * @author yoominic
 * @since 2025-03-14
 */
@Api(tags = "承租人关系记录表")
@RestController
@RequestMapping("/tenantRelationship")
public class TenantRelationshipController {

    @Autowired
    private TenantRelationshipMapper tenantRelationshipMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private YonghuMapper yonghuMapper;

    @Autowired
    private FwMapper fwMapper;


    @ApiOperation(value = "获取承租人关系记录列表", notes = "获取承租人关系记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "isRealName", value = "是否实名 0否 1是", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "status", value = "状态 0无效 1租赁中 2已退租 3已变更", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "haveNewDeposit", value = "保证金缴纳状态 0未缴纳 1已缴纳 2已退还", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "houseType", value = "房源类型", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "fwkeyword", value = "房屋关键字（租赁证编号、地址）", required = false, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "yhkeyword", value = "承租人关键字（姓名、身份证号、手机号）", required = false, paramType = "query", dataType = "string")
    })
    @GetMapping("admin/getTenantRelationship")
    public Result getTenantRelationship(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                        @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                        String isRealName,String status,String haveNewDeposit,String houseType,String fwkeyword,
                                        String yhkeyword) {
        Page<TenantRelationship> pageParam = new Page<>(page, limit);

        IPage<TenantRelationship> pageResult = tenantRelationshipMapper.queryTenanRelationship(pageParam, isRealName,status,haveNewDeposit,houseType,fwkeyword,yhkeyword);
        for (TenantRelationship tenantRelationship : pageResult.getRecords()){
            String familyMembersJsonStr = tenantRelationship.getFamilyMembersJson();
            if (familyMembersJsonStr != null && !familyMembersJsonStr.equals("")){
                JSONArray array = JSONArray.parseArray(familyMembersJsonStr);
                tenantRelationship.setFamilyMembers(array);
                tenantRelationship.setFamilyMembersCount(array.size());
            }
            // 处理 houseInfo
            String houseInfoJson = tenantRelationship.getHouseInfo();
            if (houseInfoJson != null && !houseInfoJson.isEmpty()) {
                tenantRelationship.setHouseInfo(houseInfoJson);  // 自动解析为 List<Map<String, Object>>
                tenantRelationship.setHouseInfoList(JSONArray.parseObject(houseInfoJson, new TypeReference<List<Map<String, Object>>>() {}));
            }
        }

        JSONObject result = new JSONObject();
        result.put("total", pageResult.getTotal());
        result.put("list", pageResult.getRecords());
        return Result.success(result);
    }

    @GetMapping("admin/getDistinctTenantRelationshipNew")
    public Result getDistinctTenantRelationshipNew(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                           @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                           String isRealName,String status,String haveNewDeposit,String houseType,String fwkeyword,
                                           String yhkeyword){



        return Result.success("");
    }


    @ApiOperation(value = "获取承租人关系记录详情", notes = "获取承租人关系记录详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "承租人关系记录id", required = true, paramType = "query", dataType = "int")
    })
    @GetMapping("admin/getTenantRelationshipInfoById")
    public Result getTenantRelationshipInfoById(Integer id) {
        TenantRelationship tenantRelationship = tenantRelationshipMapper.getTenantRelationshipInfoById(id);
        return Result.success(tenantRelationship);
    }


    @ApiOperation(value = "获取承租人关系记录去重列表", notes = "获取承租人关系记录去重列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "limit", value = "每页条数", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "yhkeyword", value = "承租人关键字（姓名、身份证号、手机号）", required = false, paramType = "query", dataType = "string")
    })
    @GetMapping("admin/getTenantRelationshipNew")
    public Result getTenantRelationshipNew(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                        @RequestParam(value = "limit", defaultValue = "10") Integer limit,String yhkeyword) {
        Page<TenantRelationship> pageParam = new Page<>(page, limit);
        QueryWrapper<TenantRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("tenant_name","tenant_id_card");
        if (yhkeyword != null && !yhkeyword.equals("")){
            queryWrapper.like("tenant_name", yhkeyword);
            queryWrapper.or();
            queryWrapper.like("tenant_phone", yhkeyword);
            queryWrapper.or();
            queryWrapper.like("tenant_id_card", yhkeyword);
        }
        queryWrapper.groupBy("tenant_name","tenant_id_card");
        IPage<TenantRelationship> pageResult = tenantRelationshipMapper.selectPage(pageParam, queryWrapper);
        for (TenantRelationship relationship : pageResult.getRecords()) {
            String idCard = relationship.getTenantIdCard();
            if (idCard != null && idCard.length() >= 7) {
                String newIdCard = idCard.substring(0, 3) + "*******" + idCard.substring(idCard.length() - 4);
                relationship.setTenantIdCardFour(newIdCard);
            }
        }

        JSONObject result = new JSONObject();
        result.put("total", pageResult.getTotal());
        result.put("list", pageResult.getRecords());
        return Result.success(result);
    }


    @ApiOperation(value = "根据唯一标识获取租赁关系", notes = "根据唯一标识获取租赁关系")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uniqueId", value = "唯一标识", required = true, paramType = "query", dataType = "string")
    })
    @GetMapping("admin/getTenantRelationshipById")
    public Result getFwTenantRelationships(String uniqueId) {
        QueryWrapper<TenantRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("unique_id", uniqueId);
        queryWrapper.orderByAsc("tenant_serial_number");
        List<TenantRelationship> tenantRelationships = tenantRelationshipMapper.selectList(queryWrapper);
        for (TenantRelationship tenantRelationship : tenantRelationships){

            String idCard = tenantRelationship.getTenantIdCard();
            if (idCard.length() >= 15){
                String idCard_lastFour = idCard.substring(idCard.length() - 4);
                tenantRelationship.setTenantIdCardFour(idCard_lastFour);
            }

            String familyMembersJsonStr = tenantRelationship.getFamilyMembersJson();
            if (familyMembersJsonStr != null && !familyMembersJsonStr.equals("")){
                JSONArray array = JSONArray.parseArray(familyMembersJsonStr);
                tenantRelationship.setFamilyMembers(array);
                tenantRelationship.setFamilyMembersCount(array.size());
            }
        }
        return Result.success(tenantRelationships);
    }


    @ApiOperation(value = "保存承租人关系记录", notes = "保存承租人关系记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantRelationship", value = "承租人关系记录", required = true, paramType = "body", dataType = "TenantRelationship")
    })
    @PostMapping("admin/saveTenantRelationship")
    public Result saveTenantRelationship(HttpServletRequest request, @RequestBody TenantRelationship tenantRelationship) {
        String token = request.getHeader("token");
        String userId = StpUtil.getLoginIdByToken(token).toString();
        String unique_id = tenantRelationship.getUniqueId();
        if (unique_id == null || unique_id.equals("")){
            unique_id = generateStringFromTimestamp();
        }

        //校验身份证
        if (!IDCardValidator.isValidIDCard(tenantRelationship.getTenantIdCard())){
            return Result.error("身份证号格式不正确！");
        }

        //校验手机号
        if (!PhoneValidator.isValidPhoneNumber(tenantRelationship.getTenantPhone())){
            return Result.error("手机号格式不正确！");
        }

        if (tenantRelationship.getId() == null){
            QueryWrapper<TenantRelationship> tenantRelationshipQueryWrapper = new QueryWrapper<>();
            tenantRelationshipQueryWrapper.eq("unique_id", unique_id);
            tenantRelationshipQueryWrapper.eq("tenant_id_card", tenantRelationship.getTenantIdCard());
            List<TenantRelationship> tenantRelationships = tenantRelationshipMapper.selectList(tenantRelationshipQueryWrapper);
            if (tenantRelationships.size() > 0){
                return Result.error("该身份证号已存在！");
            }
            tenantRelationship.setUniqueId(unique_id);
            tenantRelationship.setCreateTime(LocalDateTime.now());
            tenantRelationship.setCreateUser(Integer.valueOf(userId));
            tenantRelationshipMapper.insert(tenantRelationship);

            QueryWrapper<Yonghu> yonghuQueryWrapper = new QueryWrapper<>();
            yonghuQueryWrapper.eq("first_tenant_id_card", tenantRelationship.getTenantIdCard());
            yonghuQueryWrapper.last("limit 1");
            Yonghu oldYonghu = yonghuMapper.selectOne(yonghuQueryWrapper);
            if (oldYonghu == null) {
                Yonghu yonghu = new Yonghu();
                yonghu.setUniqueId(unique_id);
                yonghu.setLeaseCertificateNumber(tenantRelationship.getLeaseCertificateNumber());
                yonghu.setFirstTenantName(tenantRelationship.getTenantName());
                yonghu.setFirstTenantCompany(tenantRelationship.getTenantCompany());
                yonghu.setFirstTenantIdCard(tenantRelationship.getTenantIdCard());
                yonghu.setFirstTenantPhone(tenantRelationship.getTenantPhone());
                yonghu.setLeaseRelationshipTimeOne(tenantRelationship.getLeaseRelationshipTime());
                yonghu.setPolicyReduction(tenantRelationship.getPolicyReduction());
                yonghu.setTotalMonthlyRent(tenantRelationship.getTotalMonthlyRent());
                yonghuMapper.insert(yonghu);
            }
        }else {
            QueryWrapper<TenantRelationship> tenantRelationshipQueryWrapper = new QueryWrapper<>();
            tenantRelationshipQueryWrapper.ne("id", tenantRelationship.getId());
            tenantRelationshipQueryWrapper.eq("unique_id", unique_id);
            tenantRelationshipQueryWrapper.eq("tenant_id_card", tenantRelationship.getTenantIdCard());
            List<TenantRelationship> tenantRelationships = tenantRelationshipMapper.selectList(tenantRelationshipQueryWrapper);
            if (tenantRelationships.size() > 0){
                return Result.error("该身份证号已存在！");
            }
            tenantRelationship.setUpdateTime(LocalDateTime.now());
            tenantRelationship.setUpdateUser(Integer.valueOf(userId));
            tenantRelationshipMapper.updateById(tenantRelationship);
        }

        if (tenantRelationship.getUniqueId() != null){
            //更新房屋当前承租人信息
            QueryWrapper<TenantRelationship> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("unique_id", tenantRelationship.getUniqueId());
            queryWrapper.orderByDesc("tenant_serial_number");
            queryWrapper.last("limit 1");
            TenantRelationship lastTenantRelationship = tenantRelationshipMapper.selectOne(queryWrapper);

            QueryWrapper<Fw> fwQueryWrapper = new QueryWrapper<>();
            fwQueryWrapper.eq("id_value", tenantRelationship.getUniqueId());
            Fw fw = fwMapper.selectOne(fwQueryWrapper);
            if (fw != null){
                fw.setCurrentTenantName(lastTenantRelationship.getTenantName());
                fw.setCurrentTenantIdCard(lastTenantRelationship.getTenantIdCard());
                fwMapper.updateById(fw);
            }
        }

        return Result.success("操作成功！");
    }


    @ApiOperation(value = "添加承租人与房屋关系记录", notes = "添加承租人与房屋关系记录")
    @PostMapping("admin/addTenantRelationshipFwInfoJoin")
    public Result addTenantRelationshipFwInfoJoin(HttpServletRequest request, @RequestBody TenantRelationship tenantRelationship){

        String token = request.getHeader("token");
        String userId = StpUtil.getLoginIdByToken(token).toString();
        if (tenantRelationship.getId() == null){
            tenantRelationship.setCreateTime(LocalDateTime.now());
            tenantRelationship.setCreateUser(Integer.valueOf(userId));
            tenantRelationshipMapper.insert(tenantRelationship);
        }

        if (tenantRelationship.getId() != null){
            QueryWrapper<TenantRelationship> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", tenantRelationship.getId());
            TenantRelationship oldTenantRelationship = tenantRelationshipMapper.selectOne(queryWrapper);

            if (oldTenantRelationship.getUniqueId() == null && oldTenantRelationship.getLeaseCertificateNumber() == null){
                oldTenantRelationship.setUniqueId(tenantRelationship.getUniqueId());
                oldTenantRelationship.setLeaseCertificateNumber(tenantRelationship.getLeaseCertificateNumber());
                oldTenantRelationship.setTenantSerialNumber(1);
                tenantRelationshipMapper.updateById(oldTenantRelationship);
            }else {
                if (tenantRelationship.getType() == 1){
                    TenantRelationship tenantRelationship1 = new TenantRelationship();

                    tenantRelationship1.setFaceUrl(oldTenantRelationship.getFaceUrl());
                    tenantRelationship1.setTenantName(oldTenantRelationship.getTenantName());
                    tenantRelationship1.setTenantPhone(oldTenantRelationship.getTenantPhone());
                    tenantRelationship1.setTenantCompany(oldTenantRelationship.getTenantCompany());
                    tenantRelationship1.setTenantIdCard(oldTenantRelationship.getTenantIdCard());
                    tenantRelationship1.setFamilyMembersJson(oldTenantRelationship.getFamilyMembersJson());

                    tenantRelationship1.setUniqueId(tenantRelationship.getUniqueId());
                    tenantRelationship1.setLeaseCertificateNumber(tenantRelationship.getLeaseCertificateNumber());
                    tenantRelationship1.setTenantSerialNumber(oldTenantRelationship.getTenantSerialNumber() + 1);
                    tenantRelationship1.setCreateTime(LocalDateTime.now());
                    tenantRelationship1.setCreateUser(Integer.valueOf(userId));
                    tenantRelationshipMapper.insert(tenantRelationship1);
                }else {
                    //此处把原本绑定的房屋信息覆盖了，需要把建租时间，保证金，退还时间等信息也覆盖掉
                    tenantRelationship.setLeaseRelationshipTime(null);
                    tenantRelationship.setNewDeposit(null);
                    tenantRelationship.setNewDepositPaymentTime(null);
                    tenantRelationship.setNewDepositReturned(null);
                    tenantRelationship.setNewDepositReturnTime(null);
                    tenantRelationship.setLiveStatus(LocalDateTime.now());
                    tenantRelationship.setUpdateTime(LocalDateTime.now());
                    tenantRelationship.setUpdateUser(Integer.valueOf(userId));
                    tenantRelationshipMapper.updateById(tenantRelationship);
                }
            }
        }

        return Result.success("操作成功！");
    }


    @ApiOperation(value = "根据身份证号获取承租人关系记录", notes = "根据身份证号获取承租人关系记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tenantIdCard", value = "身份证号", required = true, paramType = "query", dataType = "string")
    })
    @GetMapping("admin/getTenantRelationshipByTenantIdCard")
    public Result getTenantRelationshipByTenantIdCard(String tenantIdCard) {

        List<TenantRelationship> tenantRelationships = tenantRelationshipMapper.getTenantRelationshipByTenantIdCard(tenantIdCard);
        return Result.success(tenantRelationships);
    }


    @ApiOperation(value = "根据id获取承租人信息", notes = "根据id获取承租人信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "承租人主键id", required = true, paramType = "query", dataType = "string")
    })
    @GetMapping("admin/getTenantRelationshipByUniqueId")
    public Result getTenantRelationshipByUniqueId(Integer id) {
        QueryWrapper<TenantRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        TenantRelationship tenantRelationship = tenantRelationshipMapper.selectOne(queryWrapper);
        return Result.success(tenantRelationship);
    }




    @ApiOperation(value = "删除承租人关系记录", notes = "删除承租人关系记录")
    @GetMapping("admin/deleteTenantRelationship")
    public Result deleteTenantRelationship(HttpServletRequest request, Integer id) {
        TenantRelationship tenantRelationship = tenantRelationshipMapper.selectById(id);
        if (tenantRelationship == null){
            return Result.error("该记录不存在！");
        }
        tenantRelationshipMapper.deleteById(id);
        //更新房屋当前承租人信息
        QueryWrapper<TenantRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("unique_id", tenantRelationship.getUniqueId());
        queryWrapper.orderByDesc("tenant_serial_number");
        queryWrapper.last("limit 1");
        TenantRelationship lastTenantRelationship = tenantRelationshipMapper.selectOne(queryWrapper);
        QueryWrapper<Fw> fwQueryWrapper = new QueryWrapper<>();
        fwQueryWrapper.eq("id_value", tenantRelationship.getUniqueId());
        fwQueryWrapper.last("limit 1");
        Fw fw = fwMapper.selectOne(fwQueryWrapper);
        fw.setCurrentTenantName(lastTenantRelationship.getTenantName());
        fw.setCurrentTenantIdCard(lastTenantRelationship.getTenantIdCard());
        fwMapper.updateById(fw);

        return Result.success("操作成功！");
    }
}

